package com.jushu.storbox;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.FileDownloadActivity.DownloadCallback;
import com.jushu.storbox.actions.Actions;
import com.jushu.storbox.callback.ICallback;
import com.jushu.storbox.callback.IDownloadThumbnailCallback;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.database.IFileDao;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.filesystem.FileManagerFactory;
import com.jushu.storbox.filesystem.iFileManager;
import com.jushu.storbox.service.CloudDriveService;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.MemoryUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.util.identity.FileMD5Identity;
import com.jushu.storbox.util.image.BitmapUtil;
import com.jushu.storbox.util.image.ImageCache;
import com.jushu.storbox.util.image.ImageCache.ImageLoader;
import com.jushu.storbox.util.image.PathHolder;
import com.jushu.storbox.util.image.PathHolder.ImageSourceState;
import com.huawei.sharedrive.sdk.android.service.CommonClient;

public class ImageViewActivity extends Activity {

	protected static final String TAG = ImageViewActivity.class.getSimpleName();

	private static final int FILE_DOWNLOAD_START = 0x91;

	private static final int FILE_DOWNLOAD_PROGRESS = 0x92;

	private static final int FILE_DOWNLOAD_SUCCESS = 0x93;

	private static final int FILE_DOWNLOAD_FAIL = 0x94;

	private static final int THUMBNAIL_UPDATA_VIEW = 0x95;

	private static final int THUMBNAIL_DOWNLOAD_START = 0x100;

	private static final int THUMBNAIL_DOWNLOAD_PROGRESS = 0x101;

	private static final int THUMBNAIL_DOWNLOAD_SUCCESS = 0x102;

	private static final int THUMBNAIL_DOWNLOAD_FAIL = 0x103;

	private static final int FILE_LOADDING_START = 0x110;

	private static final int FILE_LOADDING_PROGRESS = 0x111;

	private static final int FILE_LOADDING_SUCCESS = 0x112;

	private static final int FILE_LOADDING_FAIL = 0x113;

	private static final int FILE_LOAD_FROMLOCAL = 0x120;

	private static final int FILELIST_LOAD_FROMDATABASE = 0x130;
	
	private static final long MAX_BITMAP_CACHE_SIZE = 500 * 1020 * 1024;
	// =========================================================
	private ServiceConnection mServiceConnection = null;

	private ICloudDriveService mCloudDriveService = null;

	iFileManager mdmTools = null;

	// =========================================================
	ArrayList<IMAGE_HOLDER> viewList = new ArrayList<IMAGE_HOLDER>();

	public static final int load_failure_image = R.mipmap.empty_pic;// ////

	private ViewPager pager = null;

	FileFolderInfo selectItem = null;

	int selectedItemIndex = -1;

	private int imageWidth = 0;

	private int imageHeight = 0;
	
	ImageCache imageCache = null;
	
	ImageLoader imageLoader = new ImageLoader() {

		@Override
		public void onBeforeLoad(PathHolder item) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) item;
			Message msg = new Message();
			msg.what = FILE_LOADDING_START;
			msg.obj = holder;
			uiFreshHandler.sendMessage(msg);
		}

		@Override
		public void onLoadding(PathHolder item, int progress) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) item;
			Message msg = new Message();
			msg.what = FILE_LOADDING_PROGRESS;
			msg.obj = holder;
			msg.arg1 = progress;
			uiFreshHandler.sendMessage(msg);
		}

		@Override
		public void onLoadSuccess(PathHolder item,
				Bitmap bitmap) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) item;
			holder.addBitmapToView(bitmap);
			Message msg = new Message();
			msg.what = FILE_LOADDING_SUCCESS;
			msg.obj = holder;
			uiFreshHandler.sendMessage(msg);
		}

		@Override
		public void onLoadFail(PathHolder item, Throwable e) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) item;
			Message msg = new Message();
			msg.what = FILE_LOADDING_FAIL;
			msg.obj = holder;
			uiFreshHandler.sendMessage(msg);
		}

		@Override
		public void onDestoryed(PathHolder item) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) item;
			holder.resetUIView();
		}
	};
	
	PagerAdapter pageAdapter = new PagerAdapter() {

		private int totalItems = 0;

		@Override
		public void destroyItem(ViewGroup container, int position,
				Object object) {
			IMAGE_HOLDER holder = viewList.get(position);
			if (holder.viewContener != null) {
				holder.removeImageView();
				container.removeView(holder.viewContener);
			}
		}

		@Override
		public int getCount() {
			totalItems = viewList.size();
			return totalItems;
		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			IMAGE_HOLDER holder = viewList.get(position);
			try {
				holder.loadView();
				container.addView(holder.viewContener);
			} catch (OutOfMemoryError e) {
				Log.e(TAG, "OUT OF MEMORY");
				holder.ErrorOnLoad();
			}
			return holder;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) arg1;
			if (holder == null) {
				return false;
			}
			return holder.viewContener == arg0;
		}

	};
	
	OnPageChangeListener onPageChangeListener = new OnPageChangeListener() {

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageSelected(int arg0) {
			// viewList.get(arg0).loadImage();
		}

	};
	
	// =========================================================
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_view_image);

		mdmTools = FileManagerFactory.getFileManager(this);
		initImageCache();
		getCloudDriveService();
		getResourceFromIntent();
		initUIView();
		initViewData();
	}

	private void initImageCache() {
		WindowManager manager = getWindowManager();
		imageWidth = manager.getDefaultDisplay().getWidth();
		imageHeight = manager.getDefaultDisplay().getHeight();
		
		long availableMem = MemoryUtil.getDeviceAvailableMemory(this);
		int allocSize = (int) (availableMem * 17 / 20);
		LogUtil.d(TAG,"alloc Size is: "+allocSize);
		imageCache = new ImageCache(this, allocSize, imageWidth, imageHeight);
		imageCache.setImageLoader(imageLoader);
	}

	@Override
	protected void onDestroy() {
		unbindService(mServiceConnection);
		imageCache.evictAll();
		super.onDestroy();
	}

	// =========================================================
	private void initUIView() {
		pager = (ViewPager) findViewById(R.id.image_previse_conpent);
	}

	private void getResourceFromIntent() {
		Intent intent = getIntent();
		selectItem = (FileFolderInfo) intent.getExtras().get(
				ClientConfig.FILE_FOLDER_INFO);
	}

	private void initViewData() {
		uiFreshHandler.sendEmptyMessage(FILELIST_LOAD_FROMDATABASE);
	}

	private void getCloudDriveService() {

		mServiceConnection = new ServiceConnection() {
			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {
				mCloudDriveService = ((CloudDriveService.CenterShareDriveServiceServiceBinder) service)
						.getService();
				// UIFreshHandler.sendEmptyMessage(HAND_DRIVERSERERVICE_CONNECTED);
			}

			@Override
			public void onServiceDisconnected(ComponentName name) {
			}
		};

		Intent intent = new Intent(this, CloudDriveService.class);
		intent.setAction("tokenAlarm");
		if (null != mServiceConnection) {
			bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
		}
	}
	
	class IMAGE_HOLDER extends PathHolder {

		private static final int THUMBNAIL_HEIGHT = 128;
		private static final int THUMBNAIL_WIDTH = 128;
		public static final int FILE_IS_DOWNLOAD_NOT_BEGIN = 1;
		public static final int FILE_IS_DOWNLOAD_FINISHED = 3;
		public static final int FILE_IS_DOWNLOAD_OTHER = 4;

		private String mdmDriectory;
		private String imgaeThumbnailPath;
		private Bitmap thumbnailBmp;
		private FileFolderInfo mFileFolderInfo;
		public View viewContener;
		private RelativeLayout showImage_phase = null;
		// private ImageView image_compent;

		private RelativeLayout downloadImage_phase = null;
		private ProgressBar mProgressbar;
		private TextView download_progress_text = null;
		private ImageView progress_image;
		private IDownloadThumbnailCallback mDownloadThumbnailCallback = null;
		private ICallback mDownloadCallback = null;

		private LayoutInflater mInflater;

		ImageView contentImageView = null;
		
		ImageView tempImageView = null;
		
		private Bitmap imageBmp = null;

		public IMAGE_HOLDER(FileFolderInfo fileFolderInfo) {
			this.mFileFolderInfo = fileFolderInfo;
			mInflater = (LayoutInflater) ImageViewActivity.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			initContenerView();
			initNetHandlerCallback();
			initRelatePath();
			initDownloadState();
		}

		public void ErrorOnLoad() {
			bindingThumbnailImage();
		}

		private void initDownloadState() {
			if (mdmTools.fileIsExist(getFilePath()) && mFileFolderInfo.getTransStatus() == 3) {
				setImageState(ImageSourceState.LOAD_STATE_WHERE_LOCAL);
			} else if(mFileFolderInfo.getTransStatus() == 0) {
				setImageState(ImageSourceState.LOAD_STATE_WHERE_NETWORK);
			}
		}

		private void initRelatePath() {
			if (mFileFolderInfo.getIsInode() == -1) {
				mdmDriectory = DirectoryUtil.generateDownloadDir(ImageViewActivity.this);

				setFilePath(DirectoryUtil.generateFileDownloadPath(ImageViewActivity.this,
						mFileFolderInfo.getOwnerId(), mFileFolderInfo.getId(), mFileFolderInfo.getName()));
			} else {
				mdmDriectory = DirectoryUtil.generateShareDir(ImageViewActivity.this);

				setFilePath(DirectoryUtil.generateShareDownloadPath(ImageViewActivity.this,
						mFileFolderInfo.getOwnerBy(),
						mFileFolderInfo.getiNodeId(), 
						mFileFolderInfo.getName()));
			}

			imgaeThumbnailPath = DirectoryUtil.genThumbnailFileFullName(ImageViewActivity.this,
					mFileFolderInfo.getOwnerBy(), mFileFolderInfo.getId(),mFileFolderInfo.getName());
		}

		private void initContenerView() {

			if (viewContener == null) {
				viewContener = mInflater.inflate(R.layout.item_image_view,
						null);
			}
			downloadImage_phase = (RelativeLayout) viewContener
					.findViewById(R.id.downloadImage_phase);
			mProgressbar = (ProgressBar) viewContener
					.findViewById(R.id.progress_bar);
			download_progress_text = (TextView) viewContener
					.findViewById(R.id.progress_text);
			progress_image = (ImageView) viewContener
					.findViewById(R.id.progress_image);
			showImage_phase = (RelativeLayout) viewContener
					.findViewById(R.id.showImage_phase);
			setLoadingViewParams();
		}

		public void removeImageView() {
			if(contentImageView != null) {
				showImage_phase.removeView(contentImageView);
				contentImageView = null;
				imageBmp = null;
			}
			downloadImage_phase.setVisibility(View.VISIBLE);
			showImage_phase.setVisibility(View.INVISIBLE);
		}

		public void addImageView() {
			if(getImageState() == ImageSourceState.LOAD_STATE_WHERE_MEMERY){
				downloadImage_phase.setVisibility(View.INVISIBLE);
				showImage_phase.setVisibility(View.VISIBLE);
				// LayoutParams ps = image_compent.getLayoutParams();
				// ps.height = LayoutParams.MATCH_PARENT;
				// ps.width = LayoutParams.MATCH_PARENT;
				// image_compent.setLayoutParams(ps);
				// image_compent.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
				if (contentImageView != null) {
					RelativeLayout.LayoutParams params = null;
					if(imageBmp.getWidth() <imageWidth * 0.5 && imageBmp.getHeight() < imageHeight * 0.5){
						params = new RelativeLayout.LayoutParams(
								LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
						params.addRule(RelativeLayout.CENTER_IN_PARENT,
								RelativeLayout.TRUE);
					} else {
						params = new RelativeLayout.LayoutParams(
								LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
						params.addRule(RelativeLayout.CENTER_IN_PARENT,
								RelativeLayout.TRUE);
					}
					showImage_phase.removeAllViews();
					showImage_phase.addView(contentImageView, params);
				}
			} else {
				contentImageView = null;
				bindingThumbnailImage();
			}
		}

		private void resetUIView() {
			mProgressbar.setVisibility(View.VISIBLE);
			download_progress_text.setVisibility(View.VISIBLE);
			downloadImage_phase.setVisibility(View.VISIBLE);
			showImage_phase.setVisibility(View.INVISIBLE);
		}

		public void setLoadingViewParams() {
			LayoutParams ps = progress_image.getLayoutParams();
			ps.height = THUMBNAIL_WIDTH;
			ps.width = THUMBNAIL_HEIGHT;
			progress_image.setLayoutParams(ps);
			progress_image.setScaleType(ImageView.ScaleType.FIT_XY);
		}

		private void initNetHandlerCallback() {
			mDownloadThumbnailCallback = new IDownloadThumbnailCallback() {

				@Override
				public void onStart() {

					Message msg = new Message();
					msg.obj = IMAGE_HOLDER.this;
					msg.what = THUMBNAIL_DOWNLOAD_START;
					uiFreshHandler.sendMessage(msg);
				}

				@Override
				public void onFailure(Throwable t) {

					Message msg = new Message();
					msg.obj = IMAGE_HOLDER.this;
					msg.what = THUMBNAIL_DOWNLOAD_FAIL;
					uiFreshHandler.sendMessage(msg);
				}

				@Override
				public void onSuccess(String fileId) {
					updateThumbnail();
				}

				@Override
				public void onProgress(int currentProgress, long currentSize,
						long maxSize) {
				}

			};

			mDownloadCallback = new DownloadCallback() {

				@Override
				public void onSuccess() {
					Message msg = new Message();
					msg.obj = IMAGE_HOLDER.this;
					msg.what = FILE_DOWNLOAD_SUCCESS;
					uiFreshHandler.sendMessage(msg);
				}

				@Override
				public void onStart() {
					Message msg = new Message();
					msg.obj = IMAGE_HOLDER.this;
					msg.what = FILE_DOWNLOAD_START;
					uiFreshHandler.sendMessage(msg);
				}

				@Override
				public void onProgress(int currentProgress, long currentSize,
						long maxSize) {
					Message msg = new Message();
					msg.obj = IMAGE_HOLDER.this;
					msg.arg1 = currentProgress;
					msg.what = FILE_DOWNLOAD_PROGRESS;
					uiFreshHandler.sendMessage(msg);
				}

				@Override
				public void onFailure(Throwable t, int statusCode) {
					Message msg = new Message();
					msg.obj = IMAGE_HOLDER.this;
					msg.arg1 = statusCode;
					msg.what = FILE_DOWNLOAD_FAIL;
					uiFreshHandler.sendMessage(msg);

				}
			};

		}
		
		public void addBitmapToView(Bitmap bmp) {
			imageBmp = bmp;
			if(bmp != null && !bmp.isRecycled()) {
				contentImageView = new ImageView(ImageViewActivity.this);
				contentImageView.setImageBitmap(imageBmp);
			}
		}

 		private void getAuthorizationFromNetwork() {
			Actions actions = new Actions(ImageViewActivity.this);
			if (null != mCloudDriveService) {
				try {
					actions.smartUpdateAuthiorzation();
				} catch (Exception e) {
				}
			}
		}

		private void getAuthorizationFromLocal() {
			if (null == ShareDriveApplication.getInstance().getAuthorization()) {
				ShareDriveApplication.getInstance().setWnerID(
						PublicTools.getOwnerId(ImageViewActivity.this));
				ShareDriveApplication.getInstance().setAuthorization(
						PublicTools.getAuthorization(ImageViewActivity.this));
				SharedPreferences settings = ImageViewActivity.this
						.getSharedPreferences(ClientConfig.settings,
								Context.MODE_APPEND);
				CommonClient.getInstance().setServiceURL(
						settings.getString(ClientConfig.SERVER_ADDRESS, ""));
			}
		}

		private void loadImageFromNetwork() {
			if (!PublicTools.isAuthiorzationGotoTimeout(ImageViewActivity.this)) {
				new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							getAuthorizationFromNetwork();
							initMdmEnverimentAndDownload();
						} catch (Exception e1) {
							LogUtil.e(TAG, "Download login exception");
							e1.printStackTrace();
						}
					}
				}).start();
			} else {
				getAuthorizationFromLocal();
				initMdmEnverimentAndDownload();
			}
		}

		private void loadImageFromLocalOrMemery() {
			imageCache.loadding(this);
		}

		private void initMdmEnverimentAndDownload() {
			if (!mdmTools.fileIsExist(mdmDriectory)) {
				mdmTools.createFilePath(mdmDriectory);
			}
			if (null != mCloudDriveService) {
				doDownloadFile();
			}
		}

		private void loadThumbnail() {
			if (PublicTools.isFileType(mFileFolderInfo.getName(),
					Constant.IMAGE_TYPE)) {
				try {
					File thumBnail2 = new File(imgaeThumbnailPath);
					if (!thumBnail2.exists() && null != mCloudDriveService) {
						if (!thumBnail2.getParentFile().exists()) {
							thumBnail2.getParentFile().mkdirs();
						}
						mCloudDriveService.downloadThumbnailIcon(mFileFolderInfo.getOwnerBy(),
								mFileFolderInfo.getId(), imgaeThumbnailPath,
								mDownloadThumbnailCallback);
					} else {
						updateThumbnail();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		private void updateThumbnail() {
			Message msg = new Message();
			msg.obj = IMAGE_HOLDER.this;
			msg.what = THUMBNAIL_UPDATA_VIEW;
			uiFreshHandler.sendMessage(msg);
		}

		private void doDownloadFile() {
			if (mFileFolderInfo.getIsInode() == -1) {
				mCloudDriveService.openFile(ShareDriveApplication.getInstance()
						.getWnerID(), mFileFolderInfo.getParent(),
						mFileFolderInfo.getId(), ShareDriveApplication
								.getInstance().getAuthorization(),
						mFileFolderInfo.getSize(), getFilePath(),
						mDownloadCallback, mFileFolderInfo);
			} else {
				String shareOwnerId = "";
				if (null != mFileFolderInfo.getSharedOwnerId()) {
					shareOwnerId = mFileFolderInfo.getSharedOwnerId();
				} else if (null != mFileFolderInfo.getOwnerBy()) {
					shareOwnerId = mFileFolderInfo.getOwnerBy();
				}
				String shareId = "";
				int isInode = 0;
				if (mFileFolderInfo.getiNodeId() != null) {
					isInode = 0;
					shareId = mFileFolderInfo.getiNodeId();
				} else {
					isInode = 1;
					shareId = mFileFolderInfo.getId();
				}

				mCloudDriveService.openShareFile(shareOwnerId,
						mFileFolderInfo.getParent(), shareId,
						0, mFileFolderInfo.getSize(), getFilePath(),
						mDownloadCallback,mFileFolderInfo, isInode);
			}
		}

		public void loadView() {
			switch(getImageState()) {
				case LOAD_STATE_WHERE_LOCAL:
					loadImageFromLocalOrMemery();
					break;
				case LOAD_STATE_WHERE_MEMERY:
					loadImageFromLocalOrMemery();
					break;
				case LOAD_STATE_WHERE_NETWORK:
					loadThumbnail();
					loadImageFromNetwork();
					break;
				default:
			}
		}

		public void showProgress(String profix, int progress) {
			mProgressbar.setProgress(progress);
			download_progress_text.setText(profix + ":" + progress + "%");
		}

		public void hideProgress() {
			mProgressbar.setVisibility(View.INVISIBLE);
			download_progress_text.setVisibility(View.INVISIBLE);
		}

		public void bindingThumbnailImage() {
			if (thumbnailBmp != null && !thumbnailBmp.isRecycled()) {
				progress_image.setImageBitmap(thumbnailBmp);
			} else {
				progress_image.setImageResource(load_failure_image);
			}
		}

		public void loadThumbnailImage() {
			try {
				thumbnailBmp = BitmapUtil.GetBitmap(imgaeThumbnailPath);
			} catch (OutOfMemoryError e) {
				progress_image.setImageResource(load_failure_image);
			}
		}

		public void proccessOnLoadImageFail() {
			RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			params.addRule(RelativeLayout.CENTER_IN_PARENT,
					RelativeLayout.TRUE);
			downloadImage_phase.setVisibility(View.INVISIBLE);
//			if (thumbnailBmp != null && !thumbnailBmp.isRecycled()) {
//				progress_image.setImageBitmap(thumbnailBmp);
//				showImage_phase.removeAllViews();
//				showImage_phase.addView(progress_image, params);
//			} else {
//				showTempImageView(params);
//			}
			showTempImageView(params);
		}
		
		private void showTempImageView(RelativeLayout.LayoutParams params) {
			if(tempImageView == null){
				tempImageView = new ImageView(ImageViewActivity.this);
			}
			tempImageView.setImageResource(load_failure_image);
			showImage_phase.removeAllViews();
			showImage_phase.addView(tempImageView, params);
		}
	}

	Handler uiFreshHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if( ImageViewActivity.this == null || ImageViewActivity.this.isFinishing()) {
				return;
			}
			
			switch (msg.what) {
			case FILE_DOWNLOAD_START:
				handleDownloadBegin(msg);
				break;

			case FILE_DOWNLOAD_PROGRESS:
				handleDownloadProccess(msg);
				break;

			case FILE_DOWNLOAD_SUCCESS:
				handleDownloadSuccess(msg);
				break;

			case FILE_DOWNLOAD_FAIL:
				handleDownloadFail(msg);
				break;

			case THUMBNAIL_UPDATA_VIEW:
				handleUpdateThumbnail(msg);
				break;

			case THUMBNAIL_DOWNLOAD_START:
				handleThumbnailLoadBegin(msg);
				break;

			case THUMBNAIL_DOWNLOAD_PROGRESS:
				break;

			case THUMBNAIL_DOWNLOAD_SUCCESS:
				handleThumbnailLoadSuccess(msg);
				break;

			case THUMBNAIL_DOWNLOAD_FAIL:
				handleThumbnailLoadFail(msg);
				break;

			case FILE_LOADDING_START:
				handleFileIsLoadBegin(msg);
				break;

			case FILE_LOADDING_PROGRESS:
				handleFileIsLoadding(msg);
				break;

			case FILE_LOADDING_SUCCESS:
				handleFileLoadSuccess(msg);
				break;

			case FILE_LOADDING_FAIL:
				handleFileLoadFail(msg);
				break;

			case FILE_LOAD_FROMLOCAL:
				handleLoadFromLocal(msg);
				break;

			case FILELIST_LOAD_FROMDATABASE:
				handleLoadFromDatabase(msg);
				break;

			default:
				super.handleMessage(msg);
			}
		}

		private void handleFileIsLoadBegin(Message msg) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) msg.obj;
			holder.showProgress("Loading", 0);
		}

		private void handleFileIsLoadding(Message msg) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) msg.obj;
			holder.showProgress("Loading", msg.arg1);
		}

		private void handleLoadFromDatabase(Message msg) {
			int position = 0;
			List<FileInfo> list = DAOFactory
			.instance(ImageViewActivity.this)
			.getFileDao()
			.getFileListPage(selectItem.getOwnerId(), selectItem.getParent(), Constant.MYCLOUD_GET_FILE_LIST_STATE,
					PublicTools.getDes(ImageViewActivity.this),
                    PublicTools.getOrderBy(ImageViewActivity.this));
			
			for (int i = 0; i < list.size(); i++) {
				FileInfo tempInfo = list.get(i);

				if (tempInfo == null
						|| tempInfo.getSize() > Constant.MAX_ALLOWED_VIEW_PICTURE_SIZE
						|| tempInfo.getSize() <= 0) {
					if (tempInfo.getSize() <= 0) {
						Toast.makeText(ImageViewActivity.this, "File bad,can't open!", i).show();
					}
					continue;
				}

				if (PublicTools.isFileType(tempInfo.getName(),
						Constant.IMAGE_TYPE)) {
					IMAGE_HOLDER object = new IMAGE_HOLDER(tempInfo);
					viewList.add(object);
					if (tempInfo.getId().equals(selectItem.getId())) {
						selectedItemIndex = position;
					}
					position++;
				}
			}
			pager.setAdapter(pageAdapter);
			if (selectedItemIndex != -1) {
				pager.setCurrentItem(selectedItemIndex);
			}
			pager.setOnPageChangeListener(onPageChangeListener);
		}

		private void handleThumbnailLoadSuccess(Message msg) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) msg.obj;
			holder.loadThumbnailImage();
			holder.bindingThumbnailImage();
		}

		private void handleLoadFromLocal(Message msg) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) msg.obj;
			holder.loadImageFromLocalOrMemery();
		}

		private void handleThumbnailLoadFail(Message msg) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) msg.obj;
			holder.bindingThumbnailImage();
		}

		private void handleThumbnailLoadBegin(Message msg) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) msg.obj;
			holder.bindingThumbnailImage();
		}

		private void handleFileLoadFail(Message msg) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) msg.obj;
			holder.proccessOnLoadImageFail();
		}

		private void handleFileLoadSuccess(Message msg) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) msg.obj;
			holder.addImageView();
		}

		private void handleUpdateThumbnail(Message msg) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) msg.obj;
			holder.loadThumbnailImage();
			holder.bindingThumbnailImage();
		}

		private void handleDownloadProccess(Message msg) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) msg.obj;
			holder.showProgress("download", msg.arg1);
		}

		private void handleDownloadSuccess(Message msg) {
			
			IMAGE_HOLDER holder = (IMAGE_HOLDER) msg.obj;
			holder.showProgress("download", 100);
			holder.setImageState(ImageSourceState.LOAD_STATE_WHERE_LOCAL);
			Message downMsg = new Message();
			downMsg.obj = holder;
			downMsg.what = FILE_LOAD_FROMLOCAL;
			uiFreshHandler.sendMessage(downMsg);
		}

		private void handleDownloadFail(Message msg) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) msg.obj;
			holder.bindingThumbnailImage();
			
			if (msg.arg1 == Constant.DOWNLOAD_CANCEL_SUCCESS_CODE) {
//				Toast.makeText(getApplicationContext(),
//						getString(R.string.fileListadapter_cancel_keep),
//						Toast.LENGTH_SHORT).show();
			} else if (msg.arg1 == 901) {
				Toast.makeText(
						getApplicationContext(),
						getString(R.string.loginwait_activity_server_busy), Toast.LENGTH_SHORT).show();
			} else if(msg.arg1 == Constant.DOWNLOAD_FAIL_FILE_LARGERTHAN_CACHESIZE) {
				Toast.makeText(
						getApplicationContext(),
						getString(R.string.download_file_larger_than_local_cache), Toast.LENGTH_SHORT).show();
			}
			else {
				Toast.makeText(
						getApplicationContext(),
						getString(R.string.download_file_cache_fail) + "("
								+ msg.arg1 + ")", Toast.LENGTH_SHORT).show();
			}
		}

		private void handleDownloadBegin(Message msg) {
			IMAGE_HOLDER holder = (IMAGE_HOLDER) msg.obj;
			holder.showProgress("download", 0);
		}

	};

}
